﻿using MikuMikuLibrary.Archives;
using MikuMikuLibrary.Archives.Farc;
using MikuMikuLibrary.IO;
using MikuMikuLibrary.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ft_module_parser
{
    class ObjModify
    {
        public static void ChgShader(string[] args)
        {
            string path = args[0];
            string shd = args[1];
            if (!File.Exists(path + ".bak"))
                File.Copy(path, path + ".bak");

            using (var farcArchive = BinaryFile.Load<FarcArchive>(path + ".bak"))
            {
                foreach (var entries in farcArchive.Entries)
                {
                    var Obj = new Model();
                    if (entries.EndsWith("_obj.bin"))
                    {
                        using (var entryStream = farcArchive.Open(entries, EntryStreamMode.MemoryStream))
                        {
                            try
                            {
                                Obj.Load(entryStream);
                                foreach (var Meshes in Obj.Meshes)
                                    foreach (var Materials in Meshes.Materials)
                                        Materials.Shader = shd;

                            }
                            catch (Exception Ex)
                            {
                                Console.WriteLine("Failed to read " + entries);
                                Console.WriteLine(Ex.ToString());
                            }
                        }
                        var memStream = new MemoryStream();
                        Obj.Save(memStream, true);
                        farcArchive.Add(entries, memStream, true, ConflictPolicy.Replace);
                    }
                }
                farcArchive.Save(path);
            }
        }
    }
}
